const { useVerToken } = require('../utils/use')

// 全局拦截器
const whiteList = ['/login']

const Middleware = (req, res, next) => {
  const token = req.headers.authorization?.split(' ')[1]
  const data = useVerToken(token || '')
  if (data) {
    global.userInfo = {
      id: data?.id,
      name: data?.name
    }
  }

  // 白名单内直接跳过
  if (whiteList.includes(req._parsedUrl.pathname)) return next()

  if (!token) {
    return res.jsonFail(401, '请先登录')
  } else {
    if (!data) {
      return res.jsonFail(401)
    }
    return next()
  }

  // return res.jsonFail(404)
}

module.exports = Middleware
